package com.ycg.vue.utils;

import com.ycg.vue.Enum.MinIOPathEnum;
import com.ycg.vue.config.MinioConfig;
import com.ycg.vue.constant.Constant;
import com.ycg.vue.context.ThreadLocalContext;
import com.ycg.vue.modules.user.mapper.FileMapper;
import com.ycg.vue.result.Result;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Date;
import java.util.Objects;

/**
 * @Description minio工具类
 * @Author jink
 * @Date 2024/2/14
 */

@Component
@Slf4j
public class MinioUtils extends MinioConfig {
    @Resource
    private FileMapper fileMapper;

    public String   upload(MultipartFile file, MinIOPathEnum path) {
        try {
            String groupId = UUIDUtils.getUUID();
            String newName = path.getPath() + groupId + Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(ENDPOINT)
                    .credentials(ACCESS_KEY, SECRET_KEY)
                    .build();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(path.getRoot())
                    .object(newName)
                    .stream(file.getInputStream(), file.getSize(), -1).build();
            minioClient.putObject(putObjectArgs);
            String url = ENDPOINT + path.getRoot() + newName;
            log.info("本次上传文件大小为:{}字节", file.getSize());
            fileMapper.insert(groupId, file.getOriginalFilename(), file.getSize(),url, file.getContentType(),new Date(), ThreadLocalContext.getUserId() == null ? "newUserHead": ThreadLocalContext.getUserId());
           return groupId;
        } catch (Exception e) {
           e.printStackTrace();
            throw new RuntimeException(Constant.FILE_UPLOAD_ERROR);
        }
    }


    public Result downLoad(HttpServletResponse response, String groupId) {
        try {
            if (Objects.isNull(fileMapper.selectByGroupId(groupId))) {
                return Result.error(Constant.FILE_NOT_EXIST);
            }
            String realName = fileMapper.selectRealNameByGroupId(groupId);
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(ENDPOINT)
                    .credentials(ACCESS_KEY, SECRET_KEY)
                    .build();

            InputStream inputStream = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(BUCKET_NAME)
                    .object(realName)
                    .build());

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "attachment; filename=" + realName);

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, bytesRead);
            }
            inputStream.close();
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error(Constant.FILE_DOWN_ERROR);
        }

        return Result.success();
    }
}
